import { useState } from 'react'
import { Card, Table, Button, Space, Tag, Modal, message, Drawer, Form, Input, Select, Steps } from 'antd'
import { PlusOutlined, PlayCircleOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'
import './index.scss'

const { TextArea } = Input
const { Step } = Steps

const Workflows = () => {
  const [loading, setLoading] = useState(false)
  const [drawerVisible, setDrawerVisible] = useState(false)
  const [detailVisible, setDetailVisible] = useState(false)
  const [currentWorkflow, setCurrentWorkflow] = useState(null)
  const [form] = Form.useForm()

  // 模拟工作流数据
  const [dataSource] = useState([
    {
      id: 1,
      name: '图书信息采集流程',
      trigger: '定时触发',
      status: 'active',
      steps: 4,
      lastRun: '2024-01-20 02:00:00',
      runCount: 156,
      successRate: '98.7%',
      description: '自动爬取图书信息并入库',
      workflow: [
        { name: '爬取豆瓣图书', status: 'success' },
        { name: '数据清洗', status: 'success' },
        { name: '数据验证', status: 'success' },
        { name: '入库保存', status: 'success' },
      ],
    },
    {
      id: 2,
      name: '评论数据同步流程',
      trigger: '定时触发',
      status: 'active',
      steps: 3,
      lastRun: '2024-01-20 03:00:00',
      runCount: 89,
      successRate: '95.5%',
      description: '爬取并同步图书评论数据',
      workflow: [
        { name: '爬取评论数据', status: 'success' },
        { name: '情感分析', status: 'success' },
        { name: '数据入库', status: 'success' },
      ],
    },
    {
      id: 3,
      name: '内容审核流程',
      trigger: '事件触发',
      status: 'active',
      steps: 5,
      lastRun: '2024-01-20 10:25:00',
      runCount: 523,
      successRate: '99.2%',
      description: '用户提交内容后自动审核',
      workflow: [
        { name: '接收内容', status: 'success' },
        { name: '敏感词检测', status: 'success' },
        { name: 'AI审核', status: 'success' },
        { name: '人工复审', status: 'pending' },
        { name: '发布/拒绝', status: 'waiting' },
      ],
    },
    {
      id: 4,
      name: '数据备份流程',
      trigger: '定时触发',
      status: 'inactive',
      steps: 3,
      lastRun: '2024-01-19 00:00:00',
      runCount: 365,
      successRate: '100%',
      description: '每日数据备份流程',
      workflow: [
        { name: '数据导出', status: 'success' },
        { name: '压缩打包', status: 'success' },
        { name: '上传云端', status: 'success' },
      ],
    },
  ])

  // 触发方式配置
  const triggerConfig = {
    '定时触发': { color: 'blue' },
    '事件触发': { color: 'green' },
    '手动触发': { color: 'orange' },
  }

  // 状态配置
  const statusConfig = {
    active: { text: '运行中', color: 'success' },
    inactive: { text: '已停用', color: 'default' },
    error: { text: '错误', color: 'error' },
  }

  // 添加工作流
  const handleAdd = () => {
    form.resetFields()
    setCurrentWorkflow(null)
    setDrawerVisible(true)
  }

  // 查看详情
  const handleViewDetail = (record) => {
    setCurrentWorkflow(record)
    setDetailVisible(true)
  }

  // 执行工作流
  const handleRun = (record) => {
    Modal.confirm({
      title: '确认执行',
      content: `确定执行工作流"${record.name}"吗？`,
      onOk: () => {
        message.success('工作流已开始执行')
      },
    })
  }

  // 删除工作流
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定删除工作流"${record.name}"吗？`,
      okType: 'danger',
      onOk: () => {
        message.success('删除成功')
      },
    })
  }

  const columns = [
    {
      title: '工作流名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '触发方式',
      dataIndex: 'trigger',
      key: 'trigger',
      width: 120,
      render: (trigger) => (
        <Tag color={triggerConfig[trigger].color}>
          {trigger}
        </Tag>
      ),
    },
    {
      title: '步骤数',
      dataIndex: 'steps',
      key: 'steps',
      width: 80,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={statusConfig[status].color}>
          {statusConfig[status].text}
        </Tag>
      ),
    },
    {
      title: '上次执行',
      dataIndex: 'lastRun',
      key: 'lastRun',
      width: 160,
    },
    {
      title: '执行次数',
      dataIndex: 'runCount',
      key: 'runCount',
      width: 100,
      align: 'center',
    },
    {
      title: '成功率',
      dataIndex: 'successRate',
      key: 'successRate',
      width: 100,
      align: 'center',
      render: (rate) => (
        <span style={{ color: '#52c41a', fontWeight: 500 }}>{rate}</span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 220,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<PlayCircleOutlined />}
            onClick={() => handleRun(record)}
          >
            执行
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<DeleteOutlined />}
            danger
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="workflows-container">
      <Card className="workflows-card">
        <div className="workflows-header">
          <div>
            <h3>工作流管理</h3>
            <p>配置和管理自动化工作流程</p>
          </div>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新建工作流
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          pagination={{
            total: dataSource.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 新建/编辑工作流抽屉 */}
      <Drawer
        title={currentWorkflow ? '编辑工作流' : '新建工作流'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            label="工作流名称"
            name="name"
            rules={[{ required: true, message: '请输入工作流名称' }]}
          >
            <Input placeholder="请输入工作流名称" />
          </Form.Item>

          <Form.Item
            label="触发方式"
            name="trigger"
            rules={[{ required: true, message: '请选择触发方式' }]}
          >
            <Select placeholder="请选择触发方式">
              <Select.Option value="定时触发">定时触发</Select.Option>
              <Select.Option value="事件触发">事件触发</Select.Option>
              <Select.Option value="手动触发">手动触发</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="工作流描述"
            name="description"
          >
            <TextArea rows={4} placeholder="请输入工作流描述" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setDrawerVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 工作流详情抽屉 */}
      <Drawer
        title="工作流详情"
        width={700}
        open={detailVisible}
        onClose={() => setDetailVisible(false)}
      >
        {currentWorkflow && (
          <div className="workflow-detail">
            <div className="detail-section">
              <h4>基本信息</h4>
              <div className="info-grid">
                <div className="info-item">
                  <span className="label">工作流名称：</span>
                  <span className="value">{currentWorkflow.name}</span>
                </div>
                <div className="info-item">
                  <span className="label">触发方式：</span>
                  <Tag color={triggerConfig[currentWorkflow.trigger].color}>
                    {currentWorkflow.trigger}
                  </Tag>
                </div>
                <div className="info-item">
                  <span className="label">执行次数：</span>
                  <span className="value">{currentWorkflow.runCount}</span>
                </div>
                <div className="info-item">
                  <span className="label">成功率：</span>
                  <span className="value" style={{ color: '#52c41a' }}>
                    {currentWorkflow.successRate}
                  </span>
                </div>
              </div>
            </div>

            <div className="detail-section">
              <h4>执行流程</h4>
              <Steps
                direction="vertical"
                current={currentWorkflow.workflow.findIndex(s => s.status === 'pending')}
              >
                {currentWorkflow.workflow.map((step, index) => (
                  <Step
                    key={index}
                    title={step.name}
                    status={
                      step.status === 'success' ? 'finish' :
                      step.status === 'pending' ? 'process' :
                      step.status === 'error' ? 'error' : 'wait'
                    }
                  />
                ))}
              </Steps>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  )
}

export default Workflows
